package com.example.zy_22106107.service;

import com.example.zy_22106107.bean.UserBean;
import com.example.zy_22106107.mapper.UserMapper;
import com.example.zy_22106107.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserBean login(String username, String password) {
        return userMapper.findUserByUsernameAndPassword(username, password);
    }

    @Override
    public boolean register(String username, String email, String password) {
        UserBean existingUser = userMapper.findUserByUsername(username);
        if (existingUser == null) {
            UserBean us = new UserBean();
            us.setUsername(username);
            us.setEmail(email);
            us.setPassword(password);
            userMapper.insertUser(us);
            return true;
        }
        return false;
    }


    // 删除用户方法
    public boolean deleteJournalById(int id) {
        try {
            // 检查用户是否存在
            if (userMapper.existsById(id)) {
                userMapper.deleteById(id);
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }


    @Override
    public List<UserBean> searchJournalByTitle(String title) {
        return userMapper.findJournalByTitle(title);
    }


    @Override
    public boolean addJournal(UserBean journalBean) {
        try {
            userMapper.insertJournal(journalBean);
            return true;
        } catch (Exception e) {
            // 处理异常，比如打印日志
            return false;
        }
    }


    @Override
    public boolean updateJournal(int id, UserBean journalBean) {
        try {
            // 检查论文是否存在
            if (userMapper.LexistsById(id)) {
                journalBean.setId(id);  // 确保设置正确的ID
                userMapper.updateJournal(journalBean);  // 调用 Mapper 更新数据
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }


    // 新增的方法：通过ID查询论文
    @Override
    public UserBean searchJournalById(Long id) {
        return userMapper.findJournalById(id);
    }
}